package cn.qiyu5522.tk_ems.controller.admin;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qiyu5522.tk_ems.entity.*;
import cn.qiyu5522.tk_ems.entity.dto.QueryParamDTO;
import cn.qiyu5522.tk_ems.entity.dto.UserDTO;
import cn.qiyu5522.tk_ems.entity.vo.UserVO;
import cn.qiyu5522.tk_ems.myanotation.WebLog;
import cn.qiyu5522.tk_ems.result.CustomMapResult;
import cn.qiyu5522.tk_ems.result.R;
import cn.qiyu5522.tk_ems.service.CompanyService;
import cn.qiyu5522.tk_ems.service.StudentService;
import cn.qiyu5522.tk_ems.service.UserRoleService;
import cn.qiyu5522.tk_ems.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @BelongsProject: tk_ems
 * @BelongsPackage: cn.qiyu5522.tk_ems.controller.Admin
 * @Author: TangQi
 * @CreateTime: 2023-01-30  10:08
 * @Description: TODO
 * @Version: 1.0
 */
@Api(tags = "系统用户模块")
@RestController
@RequestMapping("/admin/user")
@Slf4j
@Validated
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private StudentService studentService;
    @Resource
    private CompanyService companyService;


    // 根据前端传来的token信息，获取用户id，返回用户信息
    @ApiOperation("获取用户信息")
    @GetMapping("/info/{token}")
    public R info(
            @NotNull(message = "token不为空")
            @ApiParam("token")
            @PathVariable String token
    ){
        // 获取指定token对应的账号id，如果未登录，则返回 null
        String loginInfo = (String) StpUtil.getLoginId();
        Long userId = Long.valueOf(loginInfo.split("-")[0]);

        // 获取用户信息
        User user = userService.getById(userId);
        return ObjectUtil.isNotEmpty(user)? R.ok().data("userInfo",user).data("token",token):R.error();
    }


    // 用户添加
    @WebLog(description = "用户新增--批量")
    @ApiOperation("菜单新增")
    @ApiImplicitParam(name = "userDTOS", value = "菜单新增", required = true,dataType = "List",dataTypeClass = List.class)
    @PostMapping("/doRegister")
    public R add(@Validated(Menu.Insert.class) @RequestBody List<UserDTO> userDTOS) {
        return userService.saveMore(userDTOS);
    }


    // 根据id修改\
    @Transactional
    @ApiOperation("用户编辑")
    @PutMapping("/doEditUser")
    public R doEditUser(@Valid @ApiParam("用户实体类对象") @RequestBody User user) {
        boolean result = userService.updateById(user);
        if(StringUtils.isNotEmpty(user.getDescription())){
            switch (user.getDescription()){
                case"学生用户":
                    if(StringUtils.isNotEmpty(user.getAvatar())){
                        // 查询学生信息
                        Student student = studentService.getById(user.getId());
                        // 更新学生头像
                        student.setAvatar(user.getAvatar());
                        studentService.updateById(student);
                    }
                    break;
                case"企业用户":
                    if(StringUtils.isNotEmpty(user.getAvatar())){
                        // 查询企业信息
                        Company company = companyService.getById(user.getId());
                        // 更新企业头像
                        company.setAvatar(user.getAvatar());
                        companyService.updateById(company);
                    }
                    break;
            }
        }
        return result ? R.ok().message("编辑成功") : R.error().message("编辑失败");
    }


    // 根据id删除
    @ApiOperation("用户删除")
    @DeleteMapping("/doDeleteUser/{id}")
    public R doDeleteUser(@NotNull(message = "id不能为空") @PathVariable String id) {
        boolean result = userService.remove(new QueryWrapper<User>().eq("username", id));
        return result ? R.ok() : R.error();
    }


    // 根据id删除
    @ApiOperation("用户查询")
    @ApiImplicitParam(name = "queryParamDTO",value = "用户分页条件查询对象")
    @PostMapping("/doQueryUser")
    public R doQueryUser(@Validated({QueryParamDTO.Query.class}) @RequestBody QueryParamDTO<UserDTO> queryParamDTO) {
        UserDTO condition = queryParamDTO.getCondition();
        IPage<User> userIPage = new Page<>(queryParamDTO.getCurrentPage(),queryParamDTO.getPageSize());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 根据名称
        userQueryWrapper.like(ObjectUtil.isNotEmpty(condition.getName()),"name", condition.getName());
        // 根据账号
        userQueryWrapper.eq(ObjectUtil.isNotEmpty(condition.getUsername()),"username", condition.getUsername());
        // 根据角色
        if(ObjectUtil.isNotEmpty(condition.getRoleId())){
            LambdaQueryWrapper<UserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserRole::getRoleId,condition.getRoleId());
            // 查询用户角色表
            List<UserRole> list = userRoleService.list(lambdaQueryWrapper);
            if(!CollectionUtil.isNotEmpty(list)){
                Map<String, Object> map = CustomMapResult.packagingResult(
                        new ArrayList(0),
                        queryParamDTO.getCurrentPage(),
                        queryParamDTO.getPageSize(),
                        userIPage.getTotal());
                return R.ok().data("userListIPage",map);
            }
            List<Long> userIds = list.stream().map(UserRole::getUserId).collect(Collectors.toList());
            userQueryWrapper.in(CollectionUtil.isNotEmpty(userIds),"id",userIds);
        }
        userService.page(userIPage,userQueryWrapper);
        // 实体类转VO
        List<UserVO> userVOS = objectMapper.convertValue(userIPage.getRecords(), new TypeReference<List<UserVO>>() {
        });
        Map<String, Object> map = CustomMapResult.packagingResult(
                userVOS,
                queryParamDTO.getCurrentPage(),
                queryParamDTO.getPageSize(),
                userIPage.getTotal());
        return R.ok().data("userListIPage",map);
    }

    // 根据id删除
    @ApiOperation("根据ID查询用户")
    @ApiImplicitParam(name = "userId",value = "用户ID")
    @GetMapping("/doQueryUserById/{userId}")
    public R doQueryUserById(@PathVariable Long userId ) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("id",userId);
        User one = userService.getOne(userQueryWrapper);
        return R.ok().data("userInfo",one);
    }

}
